/*Copyright 2014 Rajesh Putta http://www.codesnippets4all.com

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
* 
*/

package com.codesnippets4all.jthunder.extension.plugins.input.xml;

import java.util.Stack;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import com.codesnippets4all.jthunder.core.exceptions.AutomationException;

public class XmlFileHandler extends DefaultHandler{
	
	private Stack<XmlTag> tagStack=new Stack<XmlTag>();
	private StringBuilder builder=new StringBuilder();
	private XmlTag root=null;
	
	@Override
	public void startDocument() throws SAXException {
	}
	
	@Override
	public void startElement(String uri, String localName, String qName,
			Attributes attributes) throws SAXException {
		
		XmlTag tag=new XmlTag();
		tag.setName(qName);
		tag.setAttributes(attributes);
		
		tagStack.push(tag);
	}
	
	@Override
	public void characters(char[] ch, int start, int length) throws SAXException {
		builder.append(ch, start, length);
	}
	
	@Override
	public void endElement(String uri, String localName, String qName)
			throws SAXException {
		
		XmlTag tag=tagStack.peek();
		
		if(!qName.equals(tag.getName()))
		{
			throw new AutomationException("invalid XML file -> start and end tags don't match !! Start Tag::"+tag.getName()+"\tEnd Tag::"+qName);
		}
		
		tag.setBody(builder.toString());
		
		root=tagStack.pop();
		
		if(!tagStack.isEmpty())
		{
			XmlTag parent=tagStack.peek();
			
			parent.addChild(tag);
		}
		
	}
	
	@Override
	public void endDocument() throws SAXException {
		builder=null;
	}
	
	public XmlTag getRoot()
	{
		return root;
	}
}
